package com.mcc.framework.config;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;

@Configuration
public class ActiveMQConfig {

    @Bean(name = "jmsSessionFactory")
    @ConditionalOnProperty(prefix = "activemq.local", name = "enable", havingValue = "true")
    public CachingConnectionFactory connectionFactory(@Value("${activemq.local.broker-url}") String brokerUrl,
                                                        @Value("${activemq.local.user}") String userName,
                                                        @Value("${activemq.local.password}") String password) {
        return new CachingConnectionFactory(new ActiveMQConnectionFactory(userName, password, brokerUrl));
    }

    //发送
    @Bean(name = "jmsTemplate")
    @ConditionalOnProperty(prefix = "activemq.local", name = "enable", havingValue = "true")
    public JmsTemplate jmsTemplate(
            @Qualifier("jmsSessionFactory") CachingConnectionFactory connectionFactory) {
        JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
        return jmsTemplate;
    }

    //监听
    @Bean(name = "jmsQueue")
    @ConditionalOnProperty(prefix = "activemq.local", name = "enable", havingValue = "true")
    public JmsListenerContainerFactory<?> jmsQueue(@Qualifier("jmsSessionFactory") CachingConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setConnectionFactory(connectionFactory);
        bean.setPubSubDomain(false);
        return bean;
    }
}
